package com.app.controller;

import com.app.bean.Orders;
import com.app.core.ReturnVoCommon;
import com.app.service.OrdersService;
import com.app.util.StringUtilsEx;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 师晓峰
 * @version V1.0
 * @date 2023/9/20 18:34
 * @Description: 用户相关的操作
 */
@Controller
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    /**
     * 订单列表，带翻页功能
     *
     * @param moviename 订单名称
     * @param page       当前第几页
     * @param rows       每页大小
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> list(String moviename, Integer page, Integer rows) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtilsEx.isEmpty(page)) {
            page = 1;
        }
        if (StringUtilsEx.isEmpty(rows)) {
            rows = 5;
        }
        // 分页
        PageHelper.startPage(page, rows);
        List<Orders> ordersList = ordersService.list(moviename);
        map.put("rows", ordersList);
        PageInfo<Orders> pageInfo = new PageInfo<Orders>(ordersList);
        map.put("total", pageInfo.getTotal());
        return map;
    }

    /**
     * 增加/修改一个订单
     *
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public ReturnVoCommon add(Orders orders) {
        ReturnVoCommon vo = new ReturnVoCommon();
        try {
            if (StringUtilsEx.isEmpty(orders.getId())){
                ordersService.add(orders);
            }else {
                ordersService.update(orders);
            }
        } catch (Exception e) {
            vo.setCode(-1);
            vo.setErrMsg("操作失败！");
        }
        vo.setCode(0);
        return vo;
    }

    /**
     * 删除一个订单
     *
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ReturnVoCommon delete(String id) {
        ReturnVoCommon vo = new ReturnVoCommon();
        try {
            ordersService.delete(id);
        } catch (Exception e) {
            vo.setCode(-1);
            vo.setErrMsg("删除失败！");
        }
        vo.setCode(0);
        return vo;
    }

    /**
     * 查找一个订单
     *
     * @return
     */
    @RequestMapping("/getById")
    @ResponseBody
    public Orders getById(String id) {
        Orders orders = ordersService.getById(id);
        return orders;
    }



}
